package com.league.blog.system.websocket;

import com.alibaba.fastjson.JSONObject;
import com.league.blog.pojo.ArticleWithBLOBs;
import com.league.blog.system.Config;
import com.league.blog.system.redis.RedisUtils;
import com.league.blog.utils.ReflectUtil;
import com.league.blog.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @author 黄豪琦
 * 日期:2020-04-08 15:00
 * 说明:文章实时保存
 * 已弃置
 */
@Slf4j
@Controller
@ServerEndpoint(value = "/articleRealSave")
@Deprecated
public class ArticleSaveSocket {

    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;

    //concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<ArticleSaveSocket> webSocketSet = new CopyOnWriteArraySet<ArticleSaveSocket>();

    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;

    private static RedisUtils redisUtils;

    private String accountName;

    @Autowired
    public void setRedisUtils(RedisUtils redisUtils) {
        ArticleSaveSocket.redisUtils = redisUtils;
    }

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
//        session.getUserProperties().get("user");
        this.accountName = StringUtils.splitUserName(session.getUserPrincipal().getName());

        ArticleWithBLOBs articleWithBLOBs =
                (ArticleWithBLOBs) redisUtils.get(Config.getSaveInRealTimeKey() + this.accountName);
        if (articleWithBLOBs == null) {
            redisUtils.put(Config.getSaveInRealTimeKey() + this.accountName, new ArticleWithBLOBs());
        }
        webSocketSet.add(this);
        addOnlineCount();

    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() throws Exception {
        String httpSessionId = (String) ReflectUtil.getValue(session, "httpSessionId");
        //当连接关闭时 如果能从缓存中拿到文章，说明是没有保存的
        //所以给他一个文章code
        ArticleWithBLOBs articleWithBLOBs = (ArticleWithBLOBs) redisUtils.get(Config.getSaveInRealTimeKey() + httpSessionId);
        if (articleWithBLOBs != null) {
            articleWithBLOBs.setArticleCode(StringUtils.getRandomStr(5));
            redisUtils.put(Config.getSaveInRealTimeKey() + accountName, articleWithBLOBs);
        }
        webSocketSet.remove(this);
        subOnlineCount();
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) throws EncodeException {
        JSONObject jsonObject = JSONObject.parseObject(message);
        ArticleWithBLOBs articleWithBLOBs = (ArticleWithBLOBs) redisUtils.get(Config.getSaveInRealTimeKey() + accountName);
        try {
            articleWithBLOBs.setArticleTitle((String) jsonObject.get("title"));
            articleWithBLOBs.setArticleContent((String) jsonObject.get("content"));
            articleWithBLOBs.setArticleHtmlContent((String) jsonObject.get("htmlContent"));
            articleWithBLOBs.setArticleCode((String) jsonObject.get("articleCode"));

            redisUtils.put(Config.getSaveInRealTimeKey() + accountName, articleWithBLOBs);
        } catch (Exception e) {
            log.error(e.getMessage());
        }

    }

    /**
     * 发生错误时调用
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("发生错误");
        error.printStackTrace();
    }


    public void sendMessage(String message) throws IOException, EncodeException {
        this.session.getBasicRemote().sendObject(message);
    }


    /**
     * 群发自定义消息
     */
    public static void sendInfo(String message) throws IOException, EncodeException {
        for (ArticleSaveSocket item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                continue;
            }
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        ArticleSaveSocket.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        ArticleSaveSocket.onlineCount--;
    }
}
